<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="菜单名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><i-ep-search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><i-ep-refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button v-hasPerm="['industry/add']" type="success" @click="handleOpenDialog(0)">
          <template #icon><i-ep-plus /></template>
          新增
        </el-button>
      </template>

      <el-table default-expand-all v-loading="loading" :data="menuTableData" highlight-current-row row-key="id"
        :expand-row-keys="['1']" @row-click="handleRowClick" :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }">
        <el-table-column label="行业名称" min-width="200">
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success">线上</el-tag>
            <el-tag v-else type="info">线下</el-tag>
          </template>
        </el-table-column>


        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['industry/add']" v-if="scope.row.pid === 0" type="primary" link size="small"
              @click.stop="handleOpenDialog(scope.row.id)">
              <i-ep-plus />
              新增
            </el-button>

            <el-button v-hasPerm="['industry/edit']" type="primary" link size="small"
              @click.stop="handleOpenDialog(undefined, scope.row.id)">
              <i-ep-edit />
              编辑
            </el-button>
            <el-button v-hasPerm="['industry/del']" type="danger" link size="small"
              @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog" size="50%">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">

        <el-form-item label="行业名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" inline-prompt active-text="上线" inactive-text="下线" :active-value="0"
            :inactive-value="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Menu",
  inheritAttrs: false,
});

import BasicAPI, { industryVO } from "@/api/basic";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum";
import { status } from "nprogress";

const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive({
  title: "新增菜单",
  visible: false,
});

// 查询参数
const queryParams = reactive<any>({});
// 菜单表格数据
const menuTableData = ref<industryVO[]>([]);


// 初始菜单表单数据
const initialMenuFormData = ref<any>({
  status: 0,
});

// 菜单表单数据
const formData = ref({ ...initialMenuFormData.value });

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入行业名称", trigger: "blur" }],
});

// 选择表格的行菜单ID
const selectedMenuId = ref<number | undefined>();

// 查询菜单
function handleQuery() {
  loading.value = true;
  BasicAPI.getIndustryList(queryParams)
    .then((data) => {
      menuTableData.value = data as any;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 行点击事件
function handleRowClick(row: any) {
  // 记录表格选择的菜单ID，新增子菜单作为父菜单ID
  selectedMenuId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父级ID
 * @param menuId 当前ID
 */
function handleOpenDialog(parentId?: number, id?: number) {
  console.log(parentId, id);
  dialog.visible = true;
  if (id) {
    dialog.title = "编辑菜单";
    BasicAPI.getIndustryInfo({ id }).then((data: any) => {
      initialMenuFormData.value = { ...data };
      formData.value = data;
    });
  } else {
    dialog.title = "新增菜单";
    formData.value.pid = parentId;
  }
}


/** 菜单保存提交 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.value.id;
      if (menuId) {
        formData.value.id = menuId;
        BasicAPI.getIndustryUpdate(formData.value).then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        });
      } else {
        BasicAPI.getIndustryAdd(formData.value).then(() => {
          ElMessage.success("新增成功");
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除菜单
function handleDelete(menuId: number) {
  if (!menuId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      BasicAPI.getIndustryDel({ id: menuId })
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value.id = undefined;
  formData.value.redirect = "";
  formData.value.component = "";
}

onMounted(() => {
  handleQuery();
});
</script>
